java8 forEach Map List

java8 forEach 在Map和List中的使用

  • 原始的使用

Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);

for (Map.Entry<String,Integer> entry : items.entrySet()){
    System.out.println("key:"+entry.getKey()+";value:"+entry.getValue());
}
//output
A---10
B---20
C---30
D---40
E---50
F---60
  • forEach 使用方式
items.forEach((k,v)->System.out.println("key : " + k + "; value : " + v));

//output
key : A value : 10
key : B value : 20
key : C value : 30
key : D value : 40
key : E value : 50
key : F value : 60

items.forEach((k,v)->{
    System.out.println("Item : " + k + " Count : " + v);
    if("E".equals(k)){
        System.out.println("Hello E");
    }
});

key : A; value : 10
key : B; value : 20
key : C; value : 30
key : D; value : 40
key : E; value : 50
Hello E
  • java8 List 原先的使用方式

List<String> arrayList = new ArrayList<>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");

for (String item:arrayList){
    System.out.println(item);
}
  • java8 forEach 使用方式
arrayList.forEach(item->System.out.println(item));

arrayList.forEach(System.out::println);

arrayList.forEach(item->{
    if("C".equals(item)){
        System.out.println(item);
    }
});

arrayList.stream()
        .filter(s-> s.contains("B")||s.contains("C"))
        .forEach(System.out::println);

arrayList.stream()
        .filter(s->s.contains("E"))
        .findFirst().ifPresent(s -> System.out.println(s));

参考例子

java8-forEach-examples
IBM-java8-stream

  • 33
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值